/**
 * 酒店封装的方法
 * @author tong 2018-08-07
 */
// +----------------------------------------------------------------------
// | 全局变量
// | isApply        0关闭，1开启
// | orderType      0因私，1因公，-1申请单关闭时，2因公为自己，3因公为他人
// | dataInter      申请单列表数据
// | oaIndex        已选择的申请单下标
// | dateAmount     住店总天数
// | isSelectApply  是否选择过申请单
// | travelTimer    申请单出行日期
// | CITYADDRELE    城市
// | RESERVEELE     条件筛选
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 目录
// | step01:初始化方法                        _init
// +----------------------------------------------------------------------
(function (window,undefined) {
    'use strict';
    let hotelSearch = function () {
        window.CITYADDRELE  = $(".city-select");
        window.RESERVEELE   = $(".reserve");
        this._init();
    };
    hotelSearch.prototype = {
        //参数
        params: {
            hotelData       : {}
            ,isApply        : 0
            ,orderType      : 1
            ,dataInter      : {}
            ,oaIndex        : null
            ,dateAmount     : null
            ,isSelectApply  : 0
            ,travelTimer    : null
            ,isJump         : true
        },
        //step01:初始化操作
        _init: function () {
            let self = this;
            if (typeof(api) === 'undefined') {
                console.log('该插件只能在apicloud下运行');
            } else {
                self.params.hotelData = $api.getStorage('hotel_data');
                self.params.hotelData = !self.params.hotelData ? {} : JSON.parse(self.params.hotelData);
                self.isOpenExpend();
                self._initPage();
                self.cityListen();
                self._bindEv();
                setTimeout(function () {
                    self._dateSelect();
                },300);

                $(".my-location").click();
            }
        },
        //初始化页面
        _initPage : function () {
            let self = this;
            if (self.params.hotelData !== "{}") {
                window.CITYADDRELE.text(self.params.hotelData.city_name);
                $('#keyword').val(self.params.hotelData.hotel_name);
                let hotelTypes = ['商旅酒店', '现付酒店', '预付酒店'];
                $('.hotelType').attr('data-index', self.params.hotelData.hotel_type).html(hotelTypes[self.params.hotelData.hotel_type]);
            }

            //关键字搜索
            $("#keyword").blur(function(e) {
                e.preventDefault();
                let val = $.trim($(this).val());
                self.params.hotelData.keyword = val;
                $api.setStorage('hotel_data', JSON.stringify(self.params.hotelData));
            });

            $('.star-btn').click(function () {
                api.openFrame({
                    name: 'star_price_frm',
                    url: './star_price_frm.html',
                    rect: {
                        x: 0,
                        y: 0,
                        w: 'auto',
                        h: api.frameHeight + api.pageParam.H
                    },
                    bgColor: 'rgba(0,0,0,0)'
                });
            });


            //城市选择
            window.CITYADDRELE.click(function () {
                self.selectCity();
            });

            $('body').on('click','.submit',function () {
                self.search();
            });

            //获取我的位置
            $(".my-location").click(function() {
                let map = api.require('bMap');
                map.getLocationServices(function(ret, err) {
                    if (ret.enable) {
                        map.getLocation({
                            accuracy: '100m',
                            autoStop: true,
                            filter: 1
                        }, function(ret, err) {
                            if(ret.status) {
                                $showMask();
                                map.getNameFromCoords({
                                    lon: ret.lon,
                                    lat: ret.lat
                                },function(ret,err) {
                                    $hideMask();
                                    if(ret.status){
                                        if (self.params.isApply === 1 && self.params.orderType === 1 && self.params.isSelectApply === 1) {
                                            self.cityIsExist(ret.city);
                                        } else{
                                            window.CITYADDRELE.text(ret.city);
                                        }
                                    }
                                });
                            } else {
                                $alert(err.code);
                            }
                        });
                    } else {
                        $alert("未开启定位功能！");
                    }
                });
            });

            //选择因私因公
            $('.order-radio').click(function() {
                let policy = {};
                self.params.orderType = Number($("input[name='order_type']:checked").val());
                //因私
                if (self.params.orderType === 0) {
                    $('.orderN,.traves').addClass('aui-hide');
                    policy.order_type = 1;
                } else {
                    //判断出差申请单是否开启
                    if (self.params.isApply === 1) { //开启
                        $(".select-city").val('');
                        if (self.params.isSelectApply) {
                            $('.traves').removeClass('aui-hide');
                        }
                        $('.orderN').removeClass('aui-hide');
                    } else {
                        //没有开启申请单走正常流程
                        policy.order_type = -1;
                        $('.orderN').addClass('aui-hide');
                    }
                }
                $api.setStorage('trip_policy', JSON.stringify(policy));
            });

            //选择申请单
            $("#travel_id").change(function() {
                let val = $(this).val();

                if (val != -1) {
                    let i = $(this).find("option:selected").attr("data-oaIndex");
                    self.selectApply(val, i);
                } else {
                    self.params.hotelData.oaNumber = null;
                    $('.apply-info-container').addClass('qt-hide');
                }
            });
        },
        //绑定事件
        _bindEv: function() {
            let self = this;

            api.addEventListener({
                name: 'starPriceEv'
            }, function(ret) {
                console.log(JSON.stringify(ret.value.data));
                $('.star-price').empty();
                if (ret.value.data.star.length > 0 && ret.value.data.star[1] !== '不限') {
                    self.params.hotelData.StarRate = ret.value.data.star[0];
                    $('.star-price').append(ret.value.data.star[1]);
                    // console.log(parseInt(ret.value.data.price[0]));
                    // console.log(parseInt(ret.value.data.price[1]));

                } else {
                    $('.star-price').append('不限星级');
                    self.params.hotelData.StarRate = '';
                }

                if (parseInt(ret.value.data.price[0]) === 0 && (parseInt(ret.value.data.price[1]) === 1000 || parseInt(ret.value.data.price[1]) === 0)) {
                    if (ret.value.data.star.length > 0 && ret.value.data.star[1] !== '不限') {
                        $('.star-price').append(',不限价格');
                    } else {
                        $('.star-price').append('价格');
                    }
                } else {
                    $('.star-price').append(',￥'+ret.value.data.price[0] + ' - ' + '￥' + ret.value.data.price[1]);
                }
                self.params.hotelData.LowRate = ret.value.data.price[0];
                self.params.hotelData.HighRate = ret.value.data.price[1];
            });

        },
        //日期插件
        _dateSelect: function() {
            let self = this;
            let b = new Date();
            let year = b.getFullYear();
            let mo = b.getMonth()+1;
            mo = mo<10?"0"+ mo : mo;
            let da = b.getDate();
            da = da<10?"0"+da:da;
            $('#startDate').text(mo+'-'+da);
            self.params.hotelData.arrival_date = year+"-"+mo+"-"+da;

            b = new Date(b.getTime()+24*3600*1000);
            let year1 = b.getFullYear();
            let mo1 = b.getMonth()+1;
            mo1 = mo1<10?"0" + mo1 : mo1;
            let da1 = b.getDate();
            da1 = da1<10 ? "0" + da1 : da1;
            $('#endDate').text(mo1+'-'+da1);

            $('.week').text('今天');
            $('.week1').text('明天');
            self.params.hotelData.date_amount = 1;

            self.params.hotelData.departure_date = year1+"-"+mo1+"-"+da1;

            $('.time-select').on('click',function () {
                $('.mask_calendar').show();
            });
            $('.mask_calendar').on('click',function (e) {
                if(e.target.className === "mask_calendar"){
                    $('.calendar').slideUp(200);
                    $('.mask_calendar').fadeOut(200);
                }
            });
            $('.time-select').calendarSwitch({
                selectors : {
                    sections : ".calendar"
                },
                index : 4,      //展示的月份个数
                animateFunction : "slideToggle",        //动画效果
                controlDay:true,//知否控制在daysnumber天之内，这个数值的设置前提是总显示天数大于90天
                daysnumber : "90",     //控制天数
                comeColor : "#2EB6A8",       //入住颜色
                outColor : "#2EB6A8",      //离店颜色
                comeoutColor : "#E0F4F2",        //入住和离店之间的颜色
                callback :function(startDate, endDate){//回调函数
                    $('.mask_calendar').fadeOut(200);
                    let NumDate = $('.NumDate').text();    //共多少晚
                    if (self.params.travelTimer) {
                        // console.log(startDate, self.params.travelTimer.replace(/\//g, "-"));
                        if (self.compareDate(startDate, self.params.travelTimer.replace(/\//g, "-"))) {
                            $toast("选择的出行日期小于申请单日期!");
                            self.params.isJump = false;
                            return false;
                        } else {
                            self.params.isJump = true;
                        }
                    }
                    self.params.hotelData.arrival_date = startDate;
                    self.params.hotelData.departure_date = endDate;
                    self.params.hotelData.date_amount = NumDate;
                },
                comfireBtn:'.comfire'//确定按钮的class或者id
            });
        },
        //获取出差申请开启状态
        isOpenExpend : function () {
            let self = this;
            let params = {};
            params.url = Config.common.getCompanyInfo;
            params.data = {};
            ajax(params, function(res) {
                self.params.isApply = res.apply_order;

                self.params.hotelData.isApply = self.params.isApply;

                //$api.setStorage('hotel_data', JSON.stringify(self.params.hotelData));
                if(self.params.isApply === 1){
                    $('.js-apply-select2').removeClass('qt-hide');
                    self.getApplyList();
                    let areaObj = $("#travel_id").select2();
                    areaObj.val(-1).trigger("change");
                    areaObj.change();
                } else {
                    $('.js-apply-select2').addClass('qt-hide');
                    let policy = {};
                    policy.order_type = -1;
                    $api.setStorage('trip_policy', JSON.stringify(policy));//差旅政策
                }
            })
        },
        //获取申请单列表
        getApplyList : function () {
            let self    = this,
                param   = {},
                html    = '';

            param.url   = Config.common.getApplyListOfCurrent;
            param.data  = {};

            ajax(param, function(data) {
                if (data.code === 1) {
                    // console.log(JSON.stringify(data.data));
                    self.params.dataInter = data.data;
                    for (let i in self.params.dataInter) {
                        html += '<option value="' + self.params.dataInter[i].travel_application_number + '" data-oaIndex="'+ i +'">' + self.params.dataInter[i].travel_application_number + '</option>';
                    }
                    $("#travel_id").append(html);
                } else {
                    $toast(data.msg);
                }
            })
        },
        //选择完申请单
        selectApply : function (val, i) {
            let self = this;
            let policy = {};

            self.params.isSelectApply = 1;
            self.params.oaIndex = i;
            let selected = self.params.dataInter[self.params.oaIndex];

            self.params.hotelData.oaNumber = val;
            self.params.hotelData.travelTimer = selected.travel_time;
            self.params.travelTimer = selected.travel_time;

            let timer = self.params.hotelData.arrival_date;
            if (self.compareDate(timer, self.params.travelTimer.replace(/\//g, "-"))) {
                self.params.isJump = false;
            } else {
                self.params.isJump = true;
            }

            //判读是否已经选择城市
            if (window.CITYADDRELE.text() !== '请选择城市') self.cityIsExist(window.CITYADDRELE.text());

            if (selected.business_traveler.length === 1 && selected.business_traveler[0].user_id === parseInt($api.getStorage('user_id'))) {
                //因公为自己
                policy.order_type = 2;
                $api.setStorage('travel_people', $api.getStorage('user_id'));
            } else {
                //因公为他人
                policy.order_type = 3;
                let travel_people = [];
                for (let i in selected.business_traveler) {
                    travel_people[i] = selected.business_traveler[i].user_id;
                }
                $api.setStorage('travel_people', travel_people.join(','));//出行人
            }
            let name = '';
            for (let i in selected.business_traveler) {
                name+= selected.business_traveler[i].user_name + ' ';
            }
            $('.apply-info-container').removeClass('qt-hide');
            $('.travel-time').text(selected.travel_time.replace(/\//g, "-"));
            $('.travel-city').text(selected.travel_site + '-' + selected.travel_destination);

            $('.travel-people').text(name);

            $api.setStorage('hotel_data', JSON.stringify(self.params.hotelData));
            $api.setStorage('trip_policy', JSON.stringify(policy));//差旅政策
        },
        //验证选择的城市是否在申请单行程中
        cityIsExist : function(selected) {
            let self = this;
            if (self.params.orderType === 1 && self.params.isApply === 1) {
                //判断选择的城市是否在申请单城市里
                let str = self.params.dataInter[self.params.oaIndex].travel_destination + self.params.dataInter[self.params.oaIndex].travel_site;
                if (str.indexOf(selected.substring(0,selected.length-1)) === -1) {
                    $toast('该申请单中选择的城市中不包含您当前所选城市，请重新选择！', 3000);
                    window.CITYADDRELE.html("<span class='qt-grey'>请选择城市</span>");
                } else {
                    window.CITYADDRELE.text(selected);
                }
            }
        },
        //查询
        search : function() {
            let self        = this,
                addr        = window.CITYADDRELE.text(),
                start_time  = $('#startDate').text(),
                end_time    = $('#endDate').text();
            if (addr !== '请选择城市') {
                if (start_time) {
                    if (!end_time) {
                        $toast('离开日期不能为空', 3000);
                        return false;
                    }
                } else {
                    $toast('入住日期不能为空', 3000);
                    return false;
                }
            } else {
                $toast('入住城市不能为空', 3000);
                return false;
            }
            if (self.params.orderType === 1 && self.params.isApply === 1 && !self.params.hotelData.oaNumber) {
                $toast("请选择申请单号!", 3000);
                return false;
            }
            if (!self.params.isJump) {
                $toast('请选择正确的出行日期!');
                return false;
            }
            self.params.hotelData.hotel_name = $api.trim($("#keyword").val());
            self.params.hotelData.city_name = addr;

            $api.setStorage('hotel_data', JSON.stringify(self.params.hotelData));
            api.openWin({
                name: 'list_win',
                url: './list_win.html',
                slidBackEnabled : false
            });
        },
        //入住城市跳转
        selectCity : function() {
            let self = this;

            if (Number(self.params.isApply) === 1 && Number(self.params.orderType) === 1 && !self.params.hotelData.oaNumber) {
                $toast("请先选择申请单号!", 3000);
                return false;
            }
            api.openWin({
                name: 'select_city_win',
                url: './select_city_win.html'
            });
        },
        //
        cityListen : function () {
            let self = this;
            //选择城市监听 || 验证申请单中是否包含出差地
            api.addEventListener({
                name: 'hotelAddrEv'
            }, function() {
                setTimeout(function(){
                    let a = $api.strToJson($api.getStorage('hotel_data'));
                    if (self.params.isApply === 1 && self.params.orderType === 1 && self.params.isSelectApply === 1) {
                        self.cityIsExist(a.city_name);
                    } else {
                        window.CITYADDRELE.text(a.city_name);
                    }
                },300);
            });
        },
        //比较两个日期
        compareDate : function(d1,d2) {
            let arrayD1 = d1.split("-");
            let date1 = new Date(arrayD1[0],arrayD1[1],arrayD1[2]);
            let arrayD2 = d2.split("-");
            let date2 = new Date(arrayD2[0],arrayD2[1],arrayD2[2]);
            if(date1 >= date2) return false;
            return true;
        }
    };
    window.hotelSearch = hotelSearch;
}(window, undefined));
